//
//  SecondViewController.m
//  BuffetNews
//
//  Created by 李荃荃 on 14-10-27.
//  Copyright (c) 2014年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "SecondViewController.h"
#import "NetHandler.h"
#import "SecondCollectionCell.h"
#import "UIImageView+WebCache.h"
#import "CommentViewController.h"
#import "Myflow.h"
#import "theCustom.h"
#import "otherCell.h"
#import "ArticlesNews.h"
#import "imageCollentionCell.h"
#import "MBProgressHUD.h"
#import "WebColor.h"
#import "ArtclesMode.h"
#import "NightModel.h"
#import "WebColor.h"
#import "Reachability.h"
#import <SystemConfiguration/SystemConfiguration.h>

@interface SecondViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout,UIScrollViewDelegate, UIAlertViewDelegate>
@property (nonatomic, retain) NSMutableArray * articles; // 新闻
@property (nonatomic, retain) NSString * next_url;//下一页的地址
@property (nonatomic, retain) NSString * tuijian_list_url;//下一页面精彩推荐
@property (nonatomic, retain) NSString * bgimage_url; // 新闻头条的图片地址
@property (nonatomic, retain) NSDictionary * dic; //请求数据接受
@property (nonatomic, retain) UICollectionView * collerction;


@property (nonatomic, retain) NSMutableArray * urlImage; // 图片地址
@property (nonatomic, retain) ArticlesNews * artcNews; //接受的数据
@property (nonatomic, retain) ArticlesNews * artcNews1;
@property (nonatomic, retain) ArticlesNews * artcNews2;
@property (nonatomic, retain) ArticlesNews * artcNews3;
@property (nonatomic, retain) ArticlesNews * artcNews4;
@property (nonatomic, retain) ArticlesNews * artcNews5;
@property (nonatomic, retain) ArticlesNews * artcNews6;
@property (nonatomic, retain) NSMutableArray *arrImage1;
@property (nonatomic, retain) NSMutableArray *finalArr;
@property (nonatomic, retain) UIScrollView * scroll;

@property (nonatomic, retain) UIButton * button;
@property (nonatomic, retain) MBProgressHUD * loading;
@property (nonatomic, retain) UILabel *label;
@property(nonatomic, assign) id target; // 让谁去执行方法
@property(nonatomic, assign) SEL action; // 让target去执行的方法
@property (nonatomic, assign) CGPoint point;
@property (nonatomic, assign) CGPoint point1;
@property (nonatomic, retain) UILabel *label1;
@property (nonatomic, retain) UICollectionViewFlowLayout * flowLayout;
@property (nonatomic, retain) MBProgressHUD *mbP;
@end

static int x = 1;
static int ye = 1;
@implementation SecondViewController


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        
        self.articles = [NSMutableArray array];
        self.dic = [NSDictionary dictionary];
        self.urlImage = [NSMutableArray array];
        self.arrImage1 = [NSMutableArray array];
        self.finalArr = [NSMutableArray array];

        NSNotificationCenter * censt = [NSNotificationCenter defaultCenter];
        [censt addObserver:self selector:@selector(webur:) name:@"weburl" object:nil];
    }
    return self;
}
- (void)dealloc
{
    [_articles release];
    [_next_url release];
    [_tuijian_list_url release];
    [_bgimage_url release];
    [_dic release];
    [_collerction release];
    [_urlImage release];
    [_artcNews release];
    [_artcNews1 release];
    [_artcNews2 release];
    [_artcNews3 release];
    [_artcNews4 release];
    [_artcNews5 release];
    [_artcNews6 release];
    [_arrImage1 release];
    [_finalArr release];
    [_scroll release];
    [_button release];
    [_loading release];
    [_label release];
    [_label1 release];
    [_flowLayout release];
    [_mbP release];
    [super dealloc];
}
- (void)loadingjuhua
{
    self.mbP = [[MBProgressHUD alloc] initWithView:self.collerction];
    [self.mbP setMode:MBProgressHUDModeIndeterminate];
    
    [self.mbP show:YES];
    [self.collerction addSubview:self.mbP];
    [_mbP release];
}

- (void)webur:(NSNotification *)cation
{

    CommentViewController * webComm = [[CommentViewController alloc] init];
    [webComm setModalTransitionStyle:UINavigationControllerHideShowBarDuration];
    self.button.hidden = YES ;
    webComm.webString = [cation.object objectForKey:@"weburl"];
    
    [self presentViewController:webComm animated:YES completion:^{
 
        self.button.hidden = NO;
 
    }];

}

/*
- (void)requseData1
{
    
    [self loadingjuhua];
    [NetHandler networkWithURL:self.artcNews.next_url comaletion:^(id result) {
        
        self.artcNews1 = [[ArticlesNews alloc] ModelArticlesWithDictionary:result];
        NSDictionary * data1 = [NSDictionary dictionary];
        data1 = [self.artcNews1.dic objectForKey:@"data"];
        NSDictionary * info1 = [data1 objectForKey:@"info"];
        self.artcNews1.next_url1 = [info1 objectForKey:@"next_url"];
        
        [self.finalArr addObjectsFromArray:self.artcNews1.pkArrBig];
        
        
        self.pageControl.numberOfPages = self.finalArr.count;
        [self.collerction reloadData];
        
        [self.loading removeFromSuperview];
        
    }];
    
}

- (void)requseData2
{  [self loadingjuhua];
    [NetHandler networkWithURL:self.artcNews1.next_url1 comaletion:^(id result) {
        self.artcNews2 = [[ArticlesNews alloc] ModelArticlesWithDictionary:result];


        NSDictionary * data2 = [NSDictionary dictionary];
        data2 = [self.artcNews2.dic objectForKey:@"data"];
        NSDictionary * info2 = [data2 objectForKey:@"info"];
        self.artcNews2.next_url2 = [info2 objectForKey:@"next_url"];
        [self.finalArr addObjectsFromArray:self.artcNews2.pkArrBig];
        

        
        [self.collerction reloadData];
        [self.loading removeFromSuperview];
    }];
}
- (void)requseData3
{
    [NetHandler networkWithURL:self.artcNews2.next_url2 comaletion:^(id result) {
        self.artcNews3 = [[ArticlesNews alloc] ModelArticlesWithDictionary:result];


        NSDictionary * data2 = [NSDictionary dictionary];
        data2 = [self.artcNews3.dic objectForKey:@"data"];
        NSDictionary * info2 = [data2 objectForKey:@"info"];
        self.artcNews3.next_url3 = [info2 objectForKey:@"next_url"];
        [self.finalArr addObjectsFromArray:self.artcNews3.smallArr];

        [self.collerction reloadData];
        [self.loading removeFromSuperview];
    }];
}
- (void)requseData4
{
    [NetHandler networkWithURL:self.artcNews3.next_url3 comaletion:^(id result) {
        self.artcNews4 = [[ArticlesNews alloc] ModelArticlesWithDictionary:result];
        
        NSDictionary * data2 = [NSDictionary dictionary];
        data2 = [self.artcNews4.dic objectForKey:@"data"];
        NSDictionary * info2 = [data2 objectForKey:@"info"];
        self.artcNews4.next_url4 = [info2 objectForKey:@"next_url"];
        
        [self.finalArr addObjectsFromArray:self.artcNews4.smallArr];

        [self.collerction reloadData];
        [self.loading removeFromSuperview];
    }];
}
- (void)requseData5
{
    [NetHandler networkWithURL:self.artcNews4.next_url4 comaletion:^(id result) {
        self.artcNews5 = [[ArticlesNews alloc] ModelArticlesWithDictionary:result];
        
        NSDictionary * data2 = [NSDictionary dictionary];
        data2 = [self.artcNews5.dic objectForKey:@"data"];
        NSDictionary * info2 = [data2 objectForKey:@"info"];
        self.artcNews5.next_url5 = [info2 objectForKey:@"next_url"];
        
        [self.finalArr addObjectsFromArray:self.artcNews5.smallArr];


        [self.collerction reloadData];
        [self.loading removeFromSuperview];
        
        
    }];
}
*/

// 请求数据
- (void)requestData
{
    
    
    BOOL reachable = [[Reachability reachabilityForInternetConnection] isReachable];
    
    if (!reachable) {
        UIAlertView *alertView = [[[UIAlertView alloc] initWithTitle:@"请检查您的网络连接状态" message:nil delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil] autorelease];
        [alertView show];
        
        
        
    } else {
    
    
    
    
        [NetHandler networkWithURL:self.apiString comaletion:^(id result) {

        self.artcNews = [[ArticlesNews alloc] ModelArticlesWithDictionary:result];
        [self.arrImage1 addObject:self.artcNews.bgimage_url];
        NSDictionary * imgedic = [NSDictionary dictionary];
       imgedic = result;
       
        NSDictionary * data = [NSDictionary dictionary];
        data = [self.dic objectForKey:@"data"];
        NSDictionary * info = [data objectForKey:@"info"];
        self.next_url = [info objectForKey:@"next_url"];
        self.tuijian_list_url = [info objectForKey:@"tuijian_list_url"];
        NSDictionary * ipadconfig = [data objectForKey:@"ipadconfig"];
        NSMutableArray * pages = [ipadconfig objectForKey:@"pages"];
        NSMutableArray * diy = [NSMutableArray array];
      
        for (NSDictionary * dic2 in pages) {
            
            if ([dic2 objectForKey:@"diy"] == nil) {
                self.bgimage_url = nil;
            } else {
            [diy addObject:[dic2 objectForKey:@"diy"]];
            for (NSDictionary *dic3 in diy) {
                self.bgimage_url = [dic3 objectForKey:@"bgimage_url"];
            }
            }
        }
        
        [self.finalArr addObjectsFromArray:self.artcNews.pkArrBig];

        [self.collerction reloadData];
        [self.mbP removeFromSuperview];

    }];
    }
}
-(BOOL)isReachableViaWWAN
{
    return ([[Reachability reachabilityForLocalWiFi] currentReachabilityStatus] != NotReachable);
}

- (void)startView
{
    self.flowLayout = [[UICollectionViewFlowLayout alloc] init];
    self.flowLayout.itemSize = CGSizeMake(self.view.bounds.size.width, self.view.bounds.size.height);
    self.flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    //cell之间的间距
    self.flowLayout.minimumInteritemSpacing = 0;
    //cell行之间的间距
    self.flowLayout.minimumLineSpacing = 0;
    self.flowLayout.sectionInset = UIEdgeInsetsMake(1, 0, 1, 1);

    self.collerction = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, 320, self.view.frame.size.height) collectionViewLayout:_flowLayout];
    self.collerction.delegate = self;
    self.collerction.dataSource = self;

    self.collerction.pagingEnabled = YES;

    [self.collerction registerClass:[SecondCollectionCell class] forCellWithReuseIdentifier:@"4"];
        [self.collerction registerClass:[otherCell class] forCellWithReuseIdentifier:@"1"];

    self.collerction.backgroundColor = [UIColor whiteColor];

    
    if ([NightModel shareInstance].open == 1) {
        self.collerction.backgroundColor = [WebColor dimGray];
    } else {
        self.collerction.backgroundColor = [UIColor whiteColor];
    }
    
    
    
    [self.view addSubview: self.collerction];
    
// 滚动条
     self.scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(80, self.view.frame.size.height / 80 * 76, 131, 20)];
    self.scroll.backgroundColor = [UIColor whiteColor];
    self.scroll.contentSize = CGSizeMake(130, 0);
    self.scroll.bounces = NO;

    [self.view addSubview:self.scroll];
    [self.scroll release];
    // 滚动线
    UIView * view = [[UIView alloc] initWithFrame:CGRectMake(2, 9, 140, 1)];
    view.backgroundColor = [UIColor grayColor];
    [self.scroll addSubview:view];
    [view release];
    // 拖动的按钮
    self.label = [[UILabel alloc] initWithFrame:CGRectMake(2,1,16, 16)];
    self.label.backgroundColor = [WebColor silver];
    self.label.text =[NSString stringWithFormat:@"%d", x];
    self.label.textAlignment = NSTextAlignmentCenter;
    self.label.textColor = [UIColor whiteColor];
    self.label.font = [UIFont systemFontOfSize:12];
    self.label.userInteractionEnabled = YES;
    [self.scroll addSubview:self.label];
    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(pan:)];
    pan.minimumNumberOfTouches = 1;
    pan.maximumNumberOfTouches = 1;
    [self.label addGestureRecognizer:pan];
    [pan release];
    //按钮 返回
    self.button = [UIButton buttonWithType:UIButtonTypeCustom];
    self.button.frame = CGRectMake(0, self.view.frame.size.height / 50 * 47, 35, 35);
    [self.button setBackgroundImage:[UIImage imageNamed:@"btn_home.png"] forState:UIControlStateNormal];
    
    [self.button addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.button];
    // 拖拽时现实的方框
    self.label1 = [[UILabel alloc] initWithFrame:CGRectMake(140,self.view.frame.size.height / 80 * 74,16, 16)];
    self.label1.backgroundColor = [WebColor silver];
    self.label1.font = [UIFont systemFontOfSize:12];
    self.label1.hidden = YES;
    self.label1.userInteractionEnabled = YES;
    self.label1.textColor = [UIColor whiteColor];
    self.label1.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:self.label1];
    [_label release];

    
    [self.collerction reloadData];

    [self loadingjuhua];
}



// 拖拽时调用这个方法 让laber跟着走
- (void)pan:(UIPanGestureRecognizer *)ppp
{
    NSLog(@"拽一拽");
    NSLog(@"%f", ppp.view.center.x);
    
    [UIView animateWithDuration:0.2 animations:^{
        
        if (ppp.state != UIGestureRecognizerStateEnded && ppp.state != UIGestureRecognizerStateFailed) {
            CGPoint location = [ppp locationInView:ppp.view.superview];
            
            location.y = 9;
            self.point1 = location;
            if (location.x < 9) {
                
                
//
                location.x = 10;
                self.label.text = @"1";
                self.collerction.contentOffset = CGPointMake(0, 0);
                ppp.view.center = location;
                self.label1.hidden = YES;
                self.label1.text = @"1";
                
            }else if (location.x > 40 &&location.x < 60) {
                
                self.label.text = @"2";
                
                self.collerction.contentOffset = CGPointMake(320 , 0);
                ppp.view.center = location;
                location.x = 41;
                self.label1.hidden = NO;
                self.label1.text = @"2";
            } else if (location.x > 60 &&location.x < 80) {
                
                self.collerction.contentOffset = CGPointMake(320 * 2, 0);
                self.label.text = @"3";
                ppp.view.center = location;
                 self.label1.text = @"3";
                self.label1.hidden = NO;
                location.x = 61;
            } else if (location.x > 80 &&location.x < 100) {
                self.collerction.contentOffset = CGPointMake(320 * 3, 0);
                self.label.text = @"4";
                ppp.view.center = location;
                 self.label1.text = @"4";
                self.label1.hidden = NO;
                location.x = 81;
            } else if (location.x > 100 &&location.x < 120) {
                self.collerction.contentOffset = CGPointMake(320 * 4, 0);
                self.label.text = @"5";
                 self.label1.text = @"5";
                self.label1.hidden = NO;
                ppp.view.center = location;
                location.x = 101;
            } else if (location.x > 120 &&location.x < 140) {
                self.collerction.contentOffset = CGPointMake(320 * 5, 0);
                self.label.text = @"6";
                 self.label1.text = @"6";
                self.label1.hidden = NO;
                ppp.view.center = location;
                location.x = 123;
            } else if (location.x > 123){
                
                
                location.x = 123;
                ppp.view.center = location;
                self.label1.hidden = YES;

            }
        }
    }];

}


- (void)swipe:(UISwipeGestureRecognizer *)wipe
{
//    self.button.hidden = NO;
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}

- (void)buttonClicked:(UIButton *)button
{
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}


- (void)viewDidLoad
{
    [super viewDidLoad];


    [self requestData];
    [self startView];
   
   
    [self.collerction reloadData];

}



- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.finalArr.count;
}



- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{

    SecondCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"4" forIndexPath:indexPath];



        

    cell.atcenes.pkArrBig = self.finalArr[indexPath.item];
    cell.atcenes.weburlArr = self.artcNews.weburlArr;
    cell.atcenes.bgimage_url = self.artcNews.bgimage_url;
    NSLog(@"****%d",cell.atcenes.pkArrBig.count);
    



    if ([NightModel shareInstance].open == 1) {
        
    }
    [cell resetLayout];
    [cell.collerction reloadData];
    return cell;

}
//移动一页的宽度后调用此方法
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    int i = self.collerction.contentOffset.x;
    if (self.collerction.contentOffset.x >= 0 && self.point.x >= 0 ) {
        NSLog(@"  ✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨ self.collerction.contentOffset.x = %f,  self.point.x = %f ", self.collerction.contentOffset.x , self.point.x);
        
        if (i % 320 == 0) {
            
            if ( self.collerction.contentOffset.x  - self.point.x > 0 ) {
                x++;
                ye++;
                
                self.label.center =CGPointMake(self.label.center.x + 23, 9);
                //            NSLog(@"self.label.center.x = %f", self.label.center.x);
                
                [self.label setText:[NSString stringWithFormat:@"%d", x]];
                
                if (self.point.x > (self.finalArr.count - 2) * 320) {
                    
                    self.label.center = CGPointMake(122, 9);
                    [self.label setText:[NSString stringWithFormat:@"%d", self.finalArr.count]];
                    ye = 6;
                }
                
            } else {
                
                //
                x--;
                ye--;
                self.label.center =CGPointMake(self.label.center.x - 23, 9);
                [self.label setText:[NSString stringWithFormat:@"%d", ye]];
                if (self.point.x == 0 ) {
                    self.label.center = CGPointMake(10, 9);
                    self.label.text = @"1";
                    
                }
                x = 1;
                
            }
        }
        
        
    }
    
}

//- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
//{
////    static int y = 1920;
//    
////    NSLog(@"走吗");
////    if (scrollView == self.collerction &&   self.collerction.contentOffset.x / 320 > 5 && x < 21){
//////        NSLog(@"大于么");
//////        NSLog(@"*****%f*****", self.collerction.contentOffset.x);
////        if (x == 0) {
////
//////            [self requseData1];
////            
////            x++;
////            NSLog(@"大于么1==%d",  x);
////      
////
////        } else if (self.collerction.contentOffset.x / 320 > 10 && x == 1) {
//////            [self requseData2];
////            x++;
////            NSLog(@"2");
////        } else if (self.collerction.contentOffset.x / 320 > 15 && x == 2){
//////            [self requseData3];
////            x++;
////             NSLog(@"3");
////        }
////            
////    }
//    int collerction = self.collerction.contentOffset.x;
//    NSLog(@"coller         =      %d",collerction);
////    int width = self.view.frame.size.width;
//    if (self.collerction.contentOffset.x >= 0 && self.point.x >= 0 ) {
//        NSLog(@"  ✨✨✨✨✨✨✨✨✨✨✨✨✨✨✨ self.collerction.contentOffset.x = %f,  self.point.x = %f ", self.collerction.contentOffset.x , self.point.x);
//        
//        
//            
//            if ( self.collerction.contentOffset.x  - self.point.x > 0 ) {
//                x++;
//                ye++;
//                
//                self.label.center =CGPointMake(self.label.center.x + 22, 9);
//                //            NSLog(@"self.label.center.x = %f", self.label.center.x);
//                
//                [self.label setText:[NSString stringWithFormat:@"%d", x]];
//                
//                if (self.point.x > (self.finalArr.count - 2) * 320) {
//                    
//                    self.label.center = CGPointMake(120, 9);
//                    [self.label setText:[NSString stringWithFormat:@"%d", self.finalArr.count]];
//                    ye = 6;
//                }
//                
//            } else {
//                
//                //
//                x--;
//                ye--;
//                self.label.center =CGPointMake(self.label.center.x - 22, 9);
//                [self.label setText:[NSString stringWithFormat:@"%d", ye]];
//                if (self.point.x == 0 ) {
//                    self.label.center = CGPointMake(2, 9);
//                    self.label.text = @"1";
//                    
//                }
//                x = 1;
//                
//            }
//    
//    }
////    NSLog(@"self.collerction.contentOffset.x  = %f, 320 * self.finalArr.count = %d", self.collerction.contentOffset.x * self.finalArr.count, 320 * self.finalArr.count);
//}


- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    self.point  = self.collerction.contentOffset;
}



- (void)viewDidDisappear:(BOOL)animated
{
    [self.view reloadInputViews];
    [self.view removeFromSuperview];
    x = 1;
    ye = 1;
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
